﻿using EasyXaf.EntityDesigner.BusinessObjects;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.EntityProperties;
using EasyXaf.EntityDesigner.BusinessObjects.Entities.ValidationRules;

namespace EasyXaf.EntityDesigner.Commands.PropertyTypeBuilders;

public class StringTypeBuilder : IPropertyTypeBuilder
{
    public string[] TypeAliasNames => ["string", "string!", "string?", "s", "s!", "s?", "LongString", "LongString!", "LongString?", "ls", "ls!", "ls?"];

    public void Build(EntityProperty property, string typeName, string[] typeParams)
    {
        property.PropertyType = PropertyType.String;

        if (!typeName.StartsWith("LongString", StringComparison.InvariantCultureIgnoreCase)
            || !typeName.StartsWith("ls", StringComparison.InvariantCultureIgnoreCase))
        {
            if (typeParams.Length == 1)
            {
                if (int.TryParse(typeParams[0], out int length))
                {
                    property.StringLength = length;
                }
            }
            else if (typeParams.Length > 1)
            {
                if (int.TryParse(typeParams[0], out int minLength))
                {
                    if (int.TryParse(typeParams[1], out int maxLength))
                    {
                        property.StringLength = maxLength;
                        property.Entity.ValidationRules.Add(new RangeRule(property.Session)
                        {
                            MinValue = minLength.ToString(),
                            MaxValue = maxLength.ToString(),
                            TargetProperty = property,
                        });
                    }
                }
                if (typeParams.Length > 2 && !string.IsNullOrWhiteSpace(typeParams[2]))
                {
                    property.DefaultValue = typeParams[2];
                    property.ColumnDefaultValue = typeParams[2];
                }
            }
        }

        if (typeName.EndsWith('!'))
        {
            property.IsNullable = DefaultBoolean.False;
            property.Entity.ValidationRules.Add(new RequiredRule(property.Session)
            {
                TargetProperty = property,
            });
        }
    }
}
